import * as c from '@/services/consts';
import * as api from '@/services/cdnDomain';
import * as utils from '@/utils/utils';
import { CheckCircleFilled, CloseCircleFilled, PlusOutlined,  } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from 'umi';
import { Badge, Button, Popconfirm,  } from 'antd';
import React, { useRef, useState } from 'react';
import FormDomain from './FormDomain';
import FormAccount from './FormAccount';
import FormDns from './FormDns';

const List: React.FC = (props: any) => {

  const actionRef = useRef<ActionType>();
  const { hasRight } = useModel('useAuthModel');

  const [formOpen, setFormOpen] = useState<boolean>(false);
  const [formDomainOpen, setFormDomainOpen] = useState<boolean>(false);
  const [formDnsOpen, setFormDnsOpen] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.CdnDomain | undefined>(undefined);
  
  const {
    getCdnAccountOptions,reloadCdnDomains,
  } = useModel('useGlobalModel', (model) => ({
    getCdnAccountOptions: model.getCdnAccountOptions,
    reloadCdnDomains: model.reloadCdnDomains,
  }));
  
  const handleFormSubmit = async (record: API.CdnDomain) => {
    let result: API.Result;
    if (current) {
      result = await api.cdnDomainUpdate({
        ...current,
        ...record,
      });
    } 
    else {
      result = await api.cdnDomainAdd({ ...record });
    }

    if (result && result.success === true) {
      await reloadCdnDomains();
      setCurrent(undefined);
      setFormDomainOpen(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.cdnDomainRemove({ key: id });
    if (result.success) {
      await reloadCdnDomains();
      actionRef.current?.reload();
    }
  };
  

  let columns: ProColumns<API.CdnDomain>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      search: false,
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: 'CDN供应商',
      dataIndex: 'accountType',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        allowClear: true,
        options: c.CdnSupplierTypeOptions,
      },
    },
    {
      title: 'CDN供应商',
      width: 120,
      dataIndex: 'accountType',
      hideInSearch: true,
      render: (_, record) => {
        return c.getObjectText(c.CdnSupplierTypeOptions, record.accountType);
      },
    },
    {
      title: '所属帐号',
      dataIndex: 'cdnAccountId',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        allowClear: true,
        options: getCdnAccountOptions(),
        showSearch: true,
      },
    },
    {
      title: '所属帐号',
      // align: 'center',
      width: 150,
      dataIndex: 'accountName',
      hideInSearch: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: 'DNS',
      dataIndex: 'nameServers',
      hideInSearch: true,
      render: (_, record) => {
        return record.nameServers?.join('　');
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: true,
      search: false,
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => {
        let cmps = [];
        
        if (hasRight('cdndomain_cdndomainupdate')) {
          cmps.push(
            <a
              onClick={() => {
                setFormDomainOpen(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('cdndomain_cdndomaindelete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }
        
        if (hasRight('cdndomain_cdndomaindnslist')) {
          cmps.push(
            <a
              onClick={() => {
                setFormDnsOpen(true);
                setCurrent(record);
              }}
            >
              DNS解析管理
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);
  

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        columns={columns}
        search={{
          span: 5,
          collapsed: false,
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          
          if (hasRight('cdndomain_create')) {
            toolbarDoms.push(
              <Button
                type="primary"
                key="cdndomain_create"
                onClick={() => {
                  setFormOpen(true);
                }}
              >
                CDN帐号管理
              </Button>
            );
          }

          if (hasRight('cdndomain_cdndomaincreate')) {
            toolbarDoms.push(
              <Button
                type="primary"
                key="cdndomain_cdndomaincreate"
                onClick={() => {
                  setFormDomainOpen(true);
                  setCurrent(undefined);
                }}
              >
                <PlusOutlined />
                新建域名
              </Button>
            );
          }

          return toolbarDoms;
        }}
        pagination={{
          defaultPageSize: 50,
          pageSizeOptions: [
            '50',
            '100',
            '200',
            '300',
            '500',
          ],
          hideOnSinglePage: false,
          defaultCurrent: Number(utils.getStateValue('pagecurrent') ?? 1),
        }}
        request={api.cdnDomainList}
      />
      

      <FormAccount
        open={formOpen}
        onCancel={() => {
          setFormOpen(false);
        }}
      />
      <FormDomain
        open={formDomainOpen}
        onSubmit={handleFormSubmit}
        current={current}
        onCancel={() => {
          setFormDomainOpen(false);
          setCurrent(undefined);
        }}
      />
      <FormDns
        open={formDnsOpen}
        current={current}
        onCancel={() => {
          setCurrent(undefined);
          setFormDnsOpen(false);
        }}
      />
    </PageContainer>
  );
};

export default List;
